<?php

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

class table_sings extends discuz_table
{
	public function __construct() {

		$this->_table ='er_sign_in_log';
		$this->_pk    = 'id';	

		parent::__construct();
	}

	/**
	 * 获取用户签到记录
	 * @param int $uid 用户ID
	 * @return array 用户签到记录
	 */
	public function fetch_by_uid($uid) {
		return DB::fetch_first('SELECT * FROM %t WHERE uid=%d ORDER BY dateline DESC LIMIT 1', array($this->_table, $uid));	
	}
	/**
     * 进行 insert操作
     * @param array $data 要插入的数据
     * @param bool $return_insert_id 是否返回插入ID
     * @param bool $replace 是否使用REPLACE INTO
     * @param bool $silent 是否静默模式
     * @return mixed 插入结果
     */
    public function insert($data, $return_insert_id = false, $replace = false, $silent = false) {
        return DB::insert($this->_table, $data, $return_insert_id, $replace, $silent);
    }

	// 获取用户总签到天数
    public function get_total_days($uid) {
        return DB::result_first('SELECT COUNT(*) FROM %t WHERE uid=%d', array($this->_table, $uid));
    }

    // 获取用户本月签到天数
    public function get_month_days($uid) {
		$sql = "SELECT COUNT(*) FROM ".DB::table($this->_table)." WHERE uid=".intval($uid)." AND FROM_UNIXTIME(dateline, '%Y-%m')=DATE_FORMAT(NOW(), '%Y-%m')";
		return DB::result_first($sql);
	}

    // 获取用户本月签到数据
    public function get_month_user_info($uid) {
        $sql = "SELECT dateline, credit FROM ".DB::table($this->_table)." WHERE uid=".intval($uid)." AND FROM_UNIXTIME(dateline, '%Y-%m')=DATE_FORMAT(NOW(), '%Y-%m') ORDER BY dateline ASC";
        return DB::fetch_all($sql);
    }

    // 获取今日总签到人数
	public function get_today_count() {
        $sql = "SELECT COUNT(*) FROM ".DB::table($this->_table)." WHERE FROM_UNIXTIME(dateline, '%Y-%m-%d')=CURDATE()";
        return DB::result_first($sql);
    }

    // 获取本月总签到人数
    public function get_month_count() {
        $sql = "SELECT COUNT(*) FROM ".DB::table($this->_table)." WHERE FROM_UNIXTIME(dateline, '%Y-%m')=DATE_FORMAT(NOW(), '%Y-%m')";
        return DB::result_first($sql);
    }

    // 当前用户是否签到
    public function is_signed($uid) {
        $latest_sign = $this->fetch_by_uid($uid);
        if($latest_sign && date('Y-m-d', $latest_sign['dateline']) == date('Y-m-d')) {
            return true;
        }
        return false;
    }
}